package com.msti.service;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.msti.entity.Course;
import com.msti.entity.Student;
import com.msti.sessionMgt.ApplicationSession;

public class CourseMgtDAOImpl implements CourseMgtDAO{

	@Override
	public boolean createNewCourse(Course course) {
		Session session = ApplicationSession.getSession();
		try {
			session.beginTransaction();
			session.save(course);
			session.getTransaction().commit();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
			System.out.println(he);
		}
		return true;
	}

	@Override
	public boolean deleteCourse(Course course) {
		Session session = ApplicationSession.getSession();
		try {
			session.beginTransaction();
			session.delete(course);
			session.getTransaction().commit();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
			System.out.println(he);
		}
		return true;
	}

	@Override
	public boolean editCourse(Course course) {
		Session session = ApplicationSession.getSession();
		try {
			session.beginTransaction();
			session.update(course);
			session.getTransaction().commit();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
			System.out.println(he);
		}
		return true;
	}

	@Override
	public List<Course> getAllCourse() {
		Session session = ApplicationSession.getSession();
		List<Course> allCourses = new ArrayList<Course>();
		try {
			Query query = session.createQuery("from Course");
			allCourses = query.list();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
			System.out.println(he);
		}
		return allCourses;
	}

	@Override
	public Course getCourseByName(String name) {
		Session session = ApplicationSession.getSession();
		Course course = new Course();
		try {
			Query query = session.createQuery("from Course where name = ?")
					.setParameter(0, name);
			course = (Course) query.uniqueResult();
		} catch (HibernateException he) {
			session.getTransaction().rollback();
		}
		return course;
	}

	@Override
	public Course getCourseById(long id) {
		Session session = ApplicationSession.getSession();
		Course course = new Course();
	        try {
	        	session.beginTransaction();
	            course = (Course) session.load(Course.class, id);
	            
	        } catch (HibernateException e) {
	        	session.getTransaction().rollback();
	        }
	        return course;
	}

}
